package by.dezhits.liltweets.task;

import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import by.dezhits.liltweets.http.HttpManager;

public abstract class CommonAsyncTask<T> extends
		AsyncTask<java.lang.String, java.lang.Void, T> {

	private ParamCallback<T> mParamCallback;
	
	private int mType;
	
	public CommonAsyncTask(ParamCallback<T> paramCallback, int type) {
		super();
		this.mParamCallback = paramCallback;
		this.mType = type;
	}

	private Exception e; 
	
	@Override
	protected T doInBackground(String... params) {
		try {
			String source = HttpManager.getInstance().loadAsString(params[0],mType);
			return convert(source);
		} catch (Exception e) {
			this.e = e;
		}
		return null;
	}

	public abstract T convert(String source) throws Exception;

	@Override
	protected void onPostExecute(T result) {
		super.onPostExecute(result);
		if (e != null) {
			mParamCallback.onError(e);
		} else {
			mParamCallback.onSuccess(result);
		}
	}
	
	@TargetApi(11)
	public void start(String... params) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			executeOnExecutor(THREAD_POOL_EXECUTOR, params);
		} else {
			execute(params);
		}
	}
}
